﻿using System;
using System.Windows.Automation;
using ProdControls.Interfaces;
using ProdControls.NativePatterns;
using ProdControls.UIAPatterns;
using ProdControls.Verification;
using ProdLogging;

namespace ProdControls.Bridges
{
    public static class InvokeBridge
    {
        private const string CLICK_MSG = @"Performing Click";

        /// <summary>
        ///   Handles The extended interface. event
        /// </summary>
        /// <param name="extension"> The extension interface. </param>
        /// <param name="control"> The base ProdUI control. </param>
        public static void InvokeHook(this IInvoke extension, BaseProdControl control)
        {
            try
            {
                /* Try UIA First */
                UiaInvoke(control);
            }
            catch (InvalidOperationException)
            {
                /* now try a native SendMessage */
                NativeInvoke(control);
            }
        }

        /// <summary>
        ///   Handles the UIA version of The extended interface. event
        /// </summary>
        /// <param name="control"> The UI Automation element </param>
        private static void UiaInvoke(BaseProdControl control)
        {
            AutomationEventVerifier.Register(new EventRegistrationMessage(control, InvokePattern.InvokedEvent));
            LogController.ReceiveLogMessage(new LogMessage(CLICK_MSG + control.UiaElement.Current.Name));

            InvokePatternHelper.Invoke(control.UiaElement);
        }

        /// <summary>
        ///   Send the BM_Click message to a button control
        /// </summary>
        /// <param name="control"> The UI Automation element </param>
        private static void NativeInvoke(BaseProdControl control)
        {
            if (control.UiaElement.Current.ControlType != ControlType.Button) return;

            /* should throw with no handle */
            NativeInvokeHelper.Invoke(control);
        }
    }
}